<?php
namespace App\Common\Filter;

use PhalApi\Filter;
use PhalApi\Exception\BadRequestException;

/**
 * SignFilter 简单的MD5拦截器
 *
 * - 签名的方案如下：
 *
 * + 1、排除签名参数（默认是sign）
 * + 2、将剩下的全部参数，按参数名字进行字典排序
 * + 3、将排序好的参数，全部用字符串拼接起来
 * + 4、进行md5运算
 * + 5、对系统规定时间进行比较,超时访问返回异常
 * 注意：无任何参数时，不作验签
 *
 * @package     PhalApi\Filter
 * @license     http://www.phalapi.net/license GPL 协议
 * @link        http://www.phalapi.net/
 * @author      dogstar <chanzonghuang@gmail.com> 2015-10-23
 */

class SignFilter implements Filter
{
    protected $signName;

    public function __construct($signName = 'sign', $timestampName='timestamp')
    {
        $this->signName = $signName;
        $this->timestampName = $timestampName;
    }

    public function check()
    {
        $allParams = \PhalApi\DI()->request->getAll();
        if (empty($allParams)) {
            return;
        }

        $sign = isset($allParams[$this->signName]) ? $allParams[$this->signName] : '';
        unset($allParams[$this->signName]);

        $expectSign = $this->encryptAppKey($allParams);

        if ($expectSign != $sign) {
            \PhalApi\DI()->logger->info('Wrong Sign', array('needSign' =>$expectSign));
            throw new BadRequestException(\PhalApi\T('wrong sign'), 6);
        }
        if (!isset($allParams[$this->timestampName])) {
            \PhalApi\DI()->logger->info('timestamp empty',array('needTimestamp'=>'needTimestamp'));
            throw new BadRequestException('timestamp参数不存在');
        }
        //url过期时间判断
        if (SYS_TIME-$allParams[$this->timestampName]>\PhalApi\DI()->config->get('app.expirationTime')) {
          \PhalApi\DI()->logger->info('app expirationTime',array('time'=>SYS_TIME.'|'.$allParams[$this->timestampName]));
            throw new BadRequestException('暂无响应请重试', 3);
        }
    }

    protected function encryptAppKey($params)
    {
        ksort($params);
        $paramsStrExceptSign = '';
        foreach ($params as $val) {
            $paramsStrExceptSign .= $val;
        }
        return md5($paramsStrExceptSign.\PhalApi\DI()->config->get('app.salt'));
    }
    protected function encryptAppStr($params)
    {
        ksort($params);
        $paramsStrExceptSign = '';
        foreach ($params as $val) {
            $paramsStrExceptSign .= $val;
        }
        return $paramsStrExceptSign;
        //  return md5($paramsStrExceptSign.\PhalApi\DI()->config->get('app.salt'));
    }
}
